﻿using MediatR;
using System.Transactions;
using Traceability.APP.Application.Command.Breeding;
using Traceability.APP.DTOS;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrerture.Inerfrment;
using Traceability.Infrerture.Interfaces;

namespace Traceability.APP.Application.CommandHandle.Health
{
    /// <summary>
    /// 保健信息的删除
    /// </summary>
    public class DelHealthCommandHandle:IRequestHandler<DelHealthCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Health_Model> HealthDal;

        public DelHealthCommandHandle(IBaseRepository<Health_Model> healthDal)
        {
            HealthDal = healthDal;
        }

        //public Task<APIResult<int>> Handle(DelHealthCommand request, CancellationToken cancellationToken)
        //{
        //    APIResult<int> result = new APIResult<int>();
        //    var trace = HealthDal.GetValue(request.Id).Result;
        //    trace.IsDeleted = true;

        //    var r = 0;
        //    using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        //    {
        //        r = HealthDal.Update(trace).Result;
        //        tran.Complete();
        //    }


        //    if (r > 0)
        //    {
        //        result.Code = StateCode.Ok;
        //        result.Message = "删除成功";
        //        return Task.FromResult(result);
        //    }
        //    else
        //    {
        //        result.Code = StateCode.Faile;
        //        result.Message = "删除失败";
        //        return Task.FromResult(result);
        //    }
        //}


        public Task<APIResult<int>> Handle(DelHealthCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            // 调用获取数据方法并处理可能的 null 返回
            var getValueTask = HealthDal.GetValue(request.id);
            if (getValueTask == null || getValueTask.Result == null)
            {
                result.Code = StateCode.Faile;
                result.Message = "未找到对应的健康记录，无法删除";
                return Task.FromResult(result);
            }
            var trace = getValueTask.Result;
            trace.IsDeleted = true;

            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var updateTask = HealthDal.Update(trace);
                if (updateTask != null)
                {
                    r = updateTask.Result;
                    tran.Complete();
                }
            }

            if (r > 0)
            {
                result.Code = StateCode.Ok;
                result.Message = "删除成功";
            }
            else
            {
                result.Code = StateCode.Faile;
                result.Message = "删除失败";
            }
            return Task.FromResult(result);
        }

    }
}
